package com.ks.user.service.impl;

import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.ks.core.base.OperationContext;
import com.ks.core.constant.Const;
import com.ks.core.exception.GunsException;
import com.ks.core.util.JsonUtil;
import com.ks.core.util.ToolUtil;
import com.ks.core.util.WxXmlToMapUtil;
import com.ks.user.entity.AesException;
import com.ks.user.entity.BaseSysConfig;
import com.ks.user.entity.MicroApp;
import com.ks.user.entity.WXBizMsgCrypt;
import com.ks.user.service.IBaseSysConfigService;
import com.ks.user.service.IMicroAppService;
import com.ks.user.service.IWxAuthorService;
import lombok.extern.java.Log;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author kingdee
 * @date 2020/12/23 14:04
 */
@Log
@Service
public class WxAuthorServiceImpl implements IWxAuthorService {
    @Resource
    private IBaseSysConfigService baseSysConfigService;
    @Resource
    private IMicroAppService microAppService;


    /**
     * 第三方平台appId
     */
    private static final String PLATFORM_APP_ID = "wx02bc489931300b50";

    /**
     * 第三方平台 secret
     */
    private static final String PLATFORM_APP_SECRET = "98191aaf52385af965bd035f8e8f4c54";

    /**
     * 第三方平台 消息加解密Key
     */
    private static final String PLATFORM_AES_KEY = "Ks12345678901234567890ks1234567890123456789";

    /**
     * 第三方平台 消息校验Token
     */
    private static final String PLATFORM_COMPONENT_TOKEN = "123456";

    @Override
    public String parsePequest(String timeStamp, String nonce, String msgSignature, String postData) {
        log.info("==============================开始授权事件接收URL=================================");
        try {
            //这个类是微信官网提供的解密类,需要用到消息校验Token 消息加密Key和服务平台appid
            WXBizMsgCrypt pc = new WXBizMsgCrypt(PLATFORM_COMPONENT_TOKEN, PLATFORM_AES_KEY, PLATFORM_APP_ID);
            log.info("这是PC：" + pc);
            String xml = pc.decryptMsg(msgSignature, timeStamp, nonce, postData);
            log.info("这是Xml:" + xml);
            Map<String, String> result = WxXmlToMapUtil.xmlToMap(xml);// 将xml转为map
            log.info("这是result:" + result);
            String componentVerifyTicket = MapUtils.getString(result, "ComponentVerifyTicket");
            log.info("这是ComponentVerifyTicket ：" + componentVerifyTicket);
            if (ToolUtil.isNotEmpty(componentVerifyTicket)) {
                // 存储平台授权票据,保存ticket
                BaseSysConfig baseSysConfig = baseSysConfigService.selectById("5");
                if (ToolUtil.isNotEmpty(baseSysConfig)) {
                    baseSysConfig.setConfigValue(componentVerifyTicket);
                    baseSysConfig.setUpdateTime(new Date());
                    baseSysConfigService.updateById(baseSysConfig);
                }
                log.info("====================授权票据【ComponentVerifyTicket】：【" + componentVerifyTicket + "】====================");
            } else {
                throw new RuntimeException("微信开放平台，第三方平台获取【验证票据】失败");
            }
        } catch (AesException e) {
            log.info("这是异常信息:" + e.getMessage());
            log.info("进入异常捕获。。。");
            e.printStackTrace();
        }
        log.info("==============================结束授权事件接收URL=================================");
        return "success";
    }

    @Override
    public int Commit(String template_id, String ext_json, String user_version, String user_desc,String accToken) {
        Map<String, Object> map = new HashMap<>();
        map.put("template_id", template_id);
        map.put("ext_json", ext_json);
        map.put("user_version", user_version);
        map.put("user_desc", user_desc);
        String post = HttpUtil.post("https://api.weixin.qq.com/wxa/commit?access_token=" + accToken, JsonUtil.mapToJsonStr(map));
        if (ToolUtil.isNotEmpty(post)) {
            Map<Object, Object> objectObjectMap = JsonUtil.jsonStrToMap(post);
            if (objectObjectMap.get("errcode").toString().equals("0")) {
                return 0;
            } else {
                throw new GunsException(objectObjectMap.get("errmsg").toString());
            }
        } else {
            throw new GunsException("上传代码返回值错误！！！");
        }

    }

    @Override
    public String getQrCode(OperationContext operationContext) {
        MicroApp app = getMicroApp(operationContext.getTenantId().intValue());
        if(ToolUtil.isEmpty(app)){

        }
        MicroApp microApp = microAppService.getMicroAppInfo(app.getAppId());
        String QrCode;
        if (ToolUtil.isNotEmpty(microApp)) {
            QrCode = "https://api.weixin.qq.com/wxa/get_qrcode?access_token=" + microApp.getAuthorizerAccessToken();
            return QrCode;
        } else {
            throw new GunsException("该小程序未授权在本平台！！！！");
        }
    }

    @Override
    public String SubmitAudit(String appId) {
        MicroApp microApp = microAppService.getMicroAppInfo(appId);
        if (ToolUtil.isNotEmpty(microApp)) {
            Map<String, Object> map = new HashMap<>();
            String post = HttpUtil.post(" https://api.weixin.qq.com/wxa/submit_audit?access_token=" + microApp.getAuthorizerAccessToken(), JsonUtil.mapToJsonStr(map));
            if (ToolUtil.isNotEmpty(post)) {
                Map<Object, Object> objectObjectMap = JsonUtil.jsonStrToMap(post);
                if (objectObjectMap.get("errcode").equals("0")) {
                    return objectObjectMap.get("auditid").toString();
                } else {
                    throw new GunsException("错误码:" + objectObjectMap.get("errcode").toString() + "错误信息:" + objectObjectMap.get("errmsg").toString());
                }
            } else {
                throw new GunsException("小程序代码提交审核失败！！！");
            }
        } else {
            throw new GunsException("该小程序未授权在本平台！！！！");
        }
    }

    @Override
    public Map<String, Object> getLatestAuditStatus(String appId) {
        MicroApp microApp = microAppService.getMicroAppInfo(appId);
        String s = HttpUtil.get("https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token=" + microApp.getAuthorizerAccessToken());
        if (ToolUtil.isNotEmpty(s)) {
            Map<String, Object> objectObjectMap = JsonUtil.jsonStrToMap(s);
            return objectObjectMap;
        }
        return null;
    }


    public MicroApp getMicroApp(int tenantId) {
        EntityWrapper<MicroApp> wrapper =new EntityWrapper<>();
        MicroApp microApp =new MicroApp();
        microApp.setTenantID(tenantId);
        microApp.setDelMark(Const.DEL_FLAG_NORMAL);
        wrapper.setEntity(microApp);
        MicroApp app = microAppService.selectOne(wrapper);
        return app;
    }

}
